package hjw.com.controller;

import hjw.com.entity.Cart;
import hjw.com.entity.Order;
import hjw.com.entity.OrderItem;
import hjw.com.entity.User;
import hjw.com.service.CartServiceImpl;
import hjw.com.service.OrderItemServiceImpl;
import hjw.com.service.OrderServiceImpl;
import hjw.com.service.UserServiceImpl;
import hjw.com.util.PackJsn;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>Project:Academic - OrderController
 *
 * @author IvanWei玮 -- maste
 * @version 1.0
 * @DataTime 2025/2/18 13:53
 * @since 1.8
 */
@RestController
@RequestMapping("/api/order")
public class OrderController {
    private final Logger logger = LoggerFactory.getLogger(OrderController.class);
    private final OrderServiceImpl orderDao;
    private final OrderItemServiceImpl orderItemDao;
    private final CartServiceImpl cartDao;
    private final UserServiceImpl userDao;

    @Autowired
    public OrderController(OrderServiceImpl orderDao, OrderItemServiceImpl orderItemDao, CartServiceImpl cartDao, UserServiceImpl userDao) {
        this.orderDao = orderDao;
        this.orderItemDao = orderItemDao;
        this.cartDao = cartDao;
        this.userDao = userDao;
    }

    @GetMapping("/updateSign/{ordid}")
    public String updateSign(@PathVariable("ordid") Integer ordid) {
        Object who = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (who == null){
            logger.info("未登录无法获取用户信息");
            return PackJsn.pack(401, "未登录", null);
        }
        UserDetails userDetails = (UserDetails) who;
        logger.info("获取用户信息成功");
        //获取账号
        String account = userDetails.getUsername();
        User user = userDao.findOneByAccount(account);
        if (user == null){
            logger.info("未找到用户");
            return PackJsn.pack(401, "该用户不存在", null);
        }

        Map<String, Object> params = new HashMap<>(2);
        params.put("ordid", ordid);
        params.put("shipStatus",2);
        params.put("uid", user.getId());
        int i = orderDao.updateOrder(params);
        Order order = orderDao.findByOrdid(params);
        if (i > 0){
            logger.info("订单签收成功");
            return PackJsn.pack(200, "订单签收成功", order);
        }
        logger.info("订单签收失败");
        return PackJsn.pack(203, "订单签收失败", order);
    }

    @PostMapping("/findMyOrder")
    public String findMyOrder(@RequestBody Map<String, Object> map) {
        Object who = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (who == null){
            logger.info("未登录无法获取用户信息");
            return PackJsn.pack(401, "未登录", null);
        }
        UserDetails userDetails = (UserDetails) who;
        logger.info("获取用户信息成功");
        //获取账号
        String account = userDetails.getUsername();
        User user = userDao.findOneByAccount(account);
        if (user == null){
            logger.info("未找到用户");
            return PackJsn.pack(401, "该用户不存在", null);
        }
        logger.info(map.toString());

        Map<String, Object> m = new HashMap<>(1);
        m.put("uid", user.getId());
        if (map.get("tpay") != null){
            int tpay = Integer.parseInt(map.get("tpay").toString());
            m.put("tpay", tpay);
        }
        //获取过去x天的日期
        if (map.get("pay") != null && !map.get("pay").toString().isEmpty()){
            int payStatus = Integer.parseInt(map.get("pay").toString());
            m.put("payStatus", payStatus);
        }
        if (map.get("ship") != null && !map.get("ship").toString().isEmpty()){
            int shipStatus = Integer.parseInt(map.get("ship").toString());
            m.put("shipStatus", shipStatus);
        }
        logger.info("m=" + m);
        List<Order> orders = orderDao.getOrder(m);
        if (orders == null || orders.isEmpty()){
            logger.info("用户未下单过");
            return PackJsn.pack(203, "无订单数据");
        }
        int lines = Integer.parseInt(map.get("lines").toString());


        int total = orders.size();
        //过滤查询提取
        if( lines > orders.size()){
            lines = orders.size();
        }
        Map<String, Object> returnMap = new HashMap<>(2);
        returnMap.put("total", total);
        returnMap.put("orders", orders.subList(0, lines));
        return PackJsn.pack(200, "获取用户订单成功",returnMap);
    }

    @GetMapping("/findMyOrder/{lines}")
    public String findMyOrder(@PathVariable("lines") Integer lines) {
        Object who = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (who == null){
            logger.info("未登录无法获取用户信息");
            return PackJsn.pack(401, "未登录", null);
        }
        UserDetails userDetails = (UserDetails) who;
        logger.info("获取用户信息成功");
        //获取账号
        String account = userDetails.getUsername();
        User user = userDao.findOneByAccount(account);
        if (user == null){
            logger.info("未找到用户");
            return PackJsn.pack(401, "该用户不存在", null);
        }
        Map<String, Object> map = new HashMap<>(1);
        map.put("uid", user.getId());
        logger.info("map=" + map);
        List<Order> orders = orderDao.getOrder(map);
        if (orders == null || orders.isEmpty()){
            logger.info("用户未下单过");
            return PackJsn.pack(203, "无订单数据");
        }

        if (lines == orders.size()){
            return PackJsn.pack(200, "获取用户订单成功", orders);
        }
        return PackJsn.pack(200, "获取用户订单成功", orders.subList(0, lines));
    }

    @PostMapping("/addOrder")
    public String addOrder(@RequestBody Map<String, Object> map) {
        Object who = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (who == null){
            logger.info("未登录无法获取用户信息");
            return PackJsn.pack(401, "未登录", null);
        }
        UserDetails userDetails = (UserDetails) who;
        logger.info("获取用户信息成功");
        //获取账号
        String account = userDetails.getUsername();
        User user = userDao.findOneByAccount(account);
        if (user == null){
            logger.info("未找到用户");
            return PackJsn.pack(401, "该用户不存在", null);
        }

        List<Map<String,Object>> carts = (List<Map<String, Object>>) map.get("orders");
        logger.info("订单详细："+carts);

        Double amount = Double.parseDouble(map.get("amount").toString()) ;
        String ship2name = (String) map.get("ship2name");
        String ship2phone = (String) map.get("ship2phone");
        String ship2addr = (String) map.get("ship2addr");
        logger.info("发货用户信息：{amount:"+amount+",ship2name:"+ship2name+",ship2phone:"+ship2phone+",ship2addr:"+ship2addr+"}");
        //防止跨过前端的再次校验
        if (ship2name == null || ship2phone == null || ship2addr == null){
            logger.info("发货信息不完整");
            return PackJsn.pack(203, "发货信息不完整");
        }
        if (carts == null || carts.isEmpty()){
            logger.info("订单为空");
            return PackJsn.pack(203, "订单为空");
        }
        logger.info("订单信息："+map);
        map.put("uid", user.getId());
        map.put("payStatus", 0);
        map.put("tpay", null);
        map.put("shipStatus", 0);
        map.put("shipno", "");
        map.put("ship2name", "买家-"+ship2name);
        map.put("shipper", null);
        map.put("tship", null);
        map.put("tsign", null);
        int i = orderDao.addOrder(map);
        //订单编号
        int ordid = Integer.parseInt(map.get("ordid").toString());
        for (Map<String, Object> c : carts) {
            Cart cart = new Cart();
            cart.setUid(user.getId());
            cart.setId(Integer.parseInt(c.get("id").toString()));
            cartDao.deleteCart(cart);
            OrderItem o = new OrderItem();
            o.setOrdid(ordid);
            o.getBook().setId(Integer.parseInt(((Map<String, Object>) c.get("book")).get("id").toString()));
            o.setNum(Integer.parseInt(c.get("num").toString()));
            o.setPrice(Double.parseDouble(c.get("price").toString()));
            //循环加入数据信息表
            orderItemDao.addOrderItem(o);
        }
        if (i > 0) {
            return PackJsn.pack(200, "下单成功", ordid);
        }
        return PackJsn.pack(203, "下单失败");
    }

    @GetMapping("/findByOrdid/{id}")
    public String findByOrdid(@PathVariable("id") Integer id) {
        Object who = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (who == null){
            logger.info("未登录无法获取用户信息");
            return PackJsn.pack(401, "未登录", null);
        }
        UserDetails userDetails = (UserDetails) who;
        logger.info("获取用户信息成功");
        //获取账号
        String account = userDetails.getUsername();
        User user = userDao.findOneByAccount(account);
        if (user == null){
            logger.info("未找到用户");
            return PackJsn.pack(401, "该用户不存在", null);
        }

        Map<String, Object> params = new HashMap<>(2);
        params.put("uid", user.getId());
        params.put("ordid", id);
        Order order = orderDao.findByOrdid(params);
        if (order == null){
            return PackJsn.pack(203, "订单不存在");
        }
        return PackJsn.pack(200, "查询成功", order);
    }

    @PostMapping("/addPay")
    public String addPay(@RequestParam Integer ordid) {
        Object who = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (who == null){
            logger.info("未登录无法获取用户信息");
            return PackJsn.pack(401, "未登录", null);
        }
        UserDetails userDetails = (UserDetails) who;
        logger.info("获取用户信息成功");
        //获取账号
        String account = userDetails.getUsername();
        User user = userDao.findOneByAccount(account);
        if (user == null){
            logger.info("未找到用户");
            return PackJsn.pack(401, "该用户不存在", null);
        }

        Map<String, Object> map = new HashMap<>(2);
        map.put("payStatus", 1);
        map.put("ordid", ordid);
        map.put("uid", user.getId());
        int i = orderDao.updateOrder(map);
        if (i == 0) {
            return PackJsn.pack(203, "订单不存在");
        }
        logger.info("修改订单状态---->" + map);
        //修改完成后，进行查询返回的更新结果
        Order order = orderDao.findByOrdid(map);
        if (order == null){
            return PackJsn.pack(203, "订单不存在");
        }
        return PackJsn.pack(200, "查询成功", order);
    }

}
